<?php 

require_once './Table.php';

use Swoole\WebSocket\Server as WebSocketServer;

class Server
{
	protected $server;

	protected $table;

	public function __construct($config)
	{
		$this->table = new Table();
		$this->server = new WebSocketServer($config['host'], $config['port']);
		$this->server->set($config['configuration']);
		$this->addEventListener();
	}

	public function addEventListener()
	{
		$this->server->on('open', [$this, 'onOpen']);
		$this->server->on('message', [$this, 'onMessage']);
		$this->server->on('close', [$this, 'onClose']);
	}

	public function onOpen($server, $request)
	{
		if ($request->get['role'] == 'commander') {
			if ($request->get['password'] != 'fuckyou123') {
				$this->server->push($request->fd, 'Not allowed connect, fake commander!!!');
				$this->server->close($request->fd);
			}

			foreach ($this->server->connections as $fd) {
				if ($fd == $this->table->commander) {
					$this->server->push($request->fd, 'Not allowed connect, commander already exists!!!');
					$this->server->close($request->fd);
				}
			}
			
			$this->table->commander = $request->fd;

		} else {
			$soliders = $this->table->soliders;

			$soliders[] = $request->fd;

			$this->table->soliders = $soliders;
		}
	}

	public function onMessage($server, $frame)
	{
		if ($frame->fd == $this->table->commander) {
			$command = $frame->data;

			foreach ($this->table->soliders as $solider) {
				$this->server->push($solider, $command);
			}
		} else {
			$this->server->push($this->table->commander, $frame->data);
		}
	}

	public function onClose($server, $fd)
	{
		$soliders = $this->table->soliders;

		if (in_array($fd, $soliders)) {
			unset($soliders[array_search($fd, $soliders)]);
		}

		if ($fd == $this->table->commander) {
			$this->table->commander = 0;
		}
	}

	public function run()
	{
		$this->server->start();
	}
}

$server = new Server([
	'host' => '0.0.0.0',
	'port' => 5178,
	'configuration' => [
		'daemonize' => 1,
	]
]);

$server->run();